<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="template_id" label="使用模板" required>
        <uni-easyinput placeholder="请输入使用的模板ID" v-model="formData.template_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="photo_count" label="图片数量">
        <uni-easyinput placeholder="需要拍摄的照片数量" type="number" v-model="formData.photo_count"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="photos" label="拍摄照片">
        <uni-file-picker 
          v-model="formData.photos" 
          file-mediatype="image" 
          :limit="9" 
          return-type="object"
          :auto-upload="true">
        </uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="result_images" label="成品图片">
        <uni-file-picker 
          v-model="formData.result_images" 
          file-mediatype="image" 
          :limit="9" 
          return-type="object"
          :auto-upload="true">
        </uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="gif_url" label="动图地址">
        <uni-easyinput placeholder="生成的GIF图片地址" v-model="formData.gif_url"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="create_date" label="创建时间" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.create_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="operator_id" label="操作员">
        <uni-data-select
          v-model="formData.operator_id"
          collection="uni-id-users"
          field="_id as value, nickname as text"
          :where="userWhere"
          placeholder="请选择操作员"
        ></uni-data-select>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/a-tasks.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'a-tasks';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  export default {
    data() {
      let formData = {
        "template_id": "",
        "photo_count": null,
        "photos": [],
        "result_images": [],
        "gif_url": "",
        "create_date": null,
        "operator_id": ""
      }
      return {
        formData,
        formDataId: "",
        userWhere: "", // 用户查询条件
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 处理图片数据结构
        if (value.photos && Array.isArray(value.photos)) {
          // 如果photos是文件对象数组（来自uni-file-picker），需要转换格式
          if (value.photos.length > 0 && value.photos[0].url) {
            value.photos = value.photos.map(item => {
              return {
                thumbnail_url: item.url,
                photo_url: item.url
              }
            });
          }
        }
        
        if (value.result_images && Array.isArray(value.result_images)) {
          // 如果result_images是文件对象数组（来自uni-file-picker），需要转换格式
          if (value.result_images.length > 0 && value.result_images[0].url) {
            value.result_images = value.result_images.map(item => {
              return {
                thumbnail_url: item.url,
                photo_url: item.url
              }
            });
          }
        }
        
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id)
          .field("template_id,photo_count,photos,result_images,gif_url,create_date,operator_id")
          .get()
          .then((res) => {
            const data = res.result.data[0]
            if (data) {
              // 预处理图片数据，使其适配uni-file-picker组件
              if (data.photos && Array.isArray(data.photos)) {
                data.photos = data.photos.map(photo => {
                  return {
                    name: '照片',
                    extname: 'jpg',
                    url: photo.photo_url || photo.thumbnail_url
                  }
                })
              }
              
              if (data.result_images && Array.isArray(data.result_images)) {
                data.result_images = data.result_images.map(image => {
                  return {
                    name: '成品图',
                    extname: 'jpg',
                    url: image.photo_url || image.thumbnail_url
                  }
                })
              }
              
              this.formData = data
            }
          }).catch((err) => {
            uni.showModal({
              content: err.message || '请求服务失败',
              showCancel: false
            })
          }).finally(() => {
            uni.hideLoading()
          })
      }
    }
  }
</script>

<style>
  .uni-container {
    padding: 15px;
  }
  
  .uni-forms-item {
    margin-bottom: 20px;
  }
  
  .uni-button-group {
    display: flex;
    margin-top: 30px;
  }
</style>
